package LinkList;

/*
旋转链表
给你一个链表的头节点 head ，旋转链表，将链表每个节点向右移动k个位置。
示例 1：
输入：head = [1,2,3,4,5], k = 2
输出：[4,5,1,2,3]
示例 2：
输入：head = [0,1,2], k = 4
输出：[2,0,1]

作者：LeetCode
链接：https://leetcode.cn/leetbook/read/linked-list/f00a2/
 */

public class _55旋转链表 {
    public static void main(String[] args) {

    }

    public class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }

    //翻转链表 ＋ 移动链表 + dummy
    public ListNode rotateRight(ListNode head, int k) {
        if(head == null){
            return head;
        }
        ListNode cur = head;
        int count = 0;
        while (cur != null) {
            count++;
            cur = cur.next;
        }

        ListNode end = reverse(head);
        ListNode dummy = new ListNode(0,end);
        cur = dummy;
        k = k % count;
        for (int i = 0; i < k; i++) {
            while (cur.next != null) {
                ListNode next = cur.next;
                cur.val = next.val;
                cur = next;
            }
            cur.val = dummy.val;
            cur = dummy;
        }

        ListNode newhead = reverse(end);

        return newhead;


    }

    public ListNode reverse(ListNode head) {
        ListNode prev = null;
        ListNode curr = head;
        while (curr != null) {
            ListNode next = curr.next;
            curr.next = prev;
            prev = curr;
            curr = next;
        }
        return prev;
    }

    //官解:闭合为环
    //这样，我们可以先将给定的链表连接成环，然后将指定位置断开。
    //数学计算规律，成环后在指定位置断开已达到旋转的效果
    class Solution {
        public ListNode rotateRight(ListNode head, int k) {
            if (k == 0 || head == null || head.next == null) {
                return head;
            }
            int n = 1;
            ListNode iter = head;
            while (iter.next != null) {
                iter = iter.next;
                n++;
            }
            int add = n - k % n;
            if (add == n) {
                return head;
            }
            iter.next = head;
            while (add-- > 0) {
                iter = iter.next;
            }
            ListNode ret = iter.next;
            iter.next = null;
            return ret;
        }
    }



}
